import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Popover } from 'antd';
import type { TooltipPlacement, TooltipTrigger } from 'antd/lib/tooltip';
import { ProfileCard } from 'gantd';
import { getOrganizationInfo } from '@/utils/organization';
import { getCodeNameSync, getCodeList } from '@/utils/codelist';
import type { OrganizationInfoProp } from '@/utils/organization';
import fields from './fields';
import request from '@/utils/request';

export interface GroupColumnProps {
  id?: string;
  data?: OrganizationInfoProp;
  children?: React.ReactNode;
  nameKey: string;
  width: number;
  placement: TooltipPlacement;
  trigger: TooltipTrigger;
  overlayClassName?: string;
}

const GroupColumn = (props: GroupColumnProps) => {
  const { id = '', data, children, nameKey, width, placement, trigger, overlayClassName } = props;

  const [codeType, setCodeType] = useState([]);
  const [popData, setPopData] = useState([]);

  const getCodeType = useCallback(async () => {
    const res: any = await getCodeList('FW_ORGANIZATION_TYPE');
    setCodeType(res);
  }, []);

  const record = useMemo(() => {
    return data || getOrganizationInfo(id);
  }, [data, id]);

  const onPopClick = useCallback(async () => {
    const data = await request.post('/security/getOrgById', { data: { id } });
    setPopData({ ...data, orgType: getCodeNameSync(codeType, data.orgType) });
  }, [id]);

  useEffect(() => {
    getCodeType();
  }, []);

  return (
    <Popover
      placement={placement}
      trigger={trigger}
      overlayClassName={overlayClassName}
      zIndex={9999}
      onClick={onPopClick}
      content={
        <div onClick={(e) => e.stopPropagation()} style={{ width }}>
          <ProfileCard
            data={popData}
            fields={fields}
            backgroundBlur={false}
            backgroundImage={false}
            showAvatar={false}
          />
        </div>
      }
    >
      {children || (
        <a
          onClick={(e) => {
            e.stopPropagation();
          }}
        >
          {record[nameKey]}
        </a>
      )}
    </Popover>
  );
};

GroupColumn.defaultProps = {
  id: '',
  width: 280,
  trigger: 'click',
  placement: 'right',
  nameKey: 'fullOrgName',
};

export default GroupColumn;
